package dao;

import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JOptionPane;

import modelo.Item;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DaoItem {
	private static SessionFactory fabrica;

	public DaoItem() throws Exception {
		fabrica = new Configuration().addClass(modelo.Item.class).buildSessionFactory();
	}

	public static boolean cadastrarItem(ArrayList<Item> listaItem) {
		try {
			
			for (Iterator<Item> iterator = listaItem.iterator(); iterator.hasNext();) {
				Item item = (Item) iterator.next();
				
				Session sessao = fabrica.openSession();
				Transaction transacao = sessao.beginTransaction();
				sessao.save(item);
				transacao.commit();
				sessao.flush();
				sessao.close();
				
			}
			
			JOptionPane.showMessageDialog(null, "Salvou os Itens");

			return true;
			
		} catch (Exception ex) {
			return false;
		}
	}

	public Item consultar(Item b) throws Exception {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();
		b = (Item) sessao.get(modelo.Item.class,b.getId_item());
		transacao.commit();
		sessao.flush();
		sessao.close();
		return b;
	}
	

	public void excluir(Item b) throws Exception {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();

		sessao.delete(b);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}

	public void alterar(Item b) throws Exception {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();

		sessao.update(b);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}

	public ArrayList<Item> consultarTodos() {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();
		Query q = sessao.createQuery("from modelo.Item");
		ArrayList<Item> Items = (ArrayList<Item>) q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return Items;
	}

	public ArrayList<Item> consultarTodos(String nome) {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();
		Query q = sessao.createQuery("from modelo.Item where nome_benef like '%" + nome + "%'");
		ArrayList<Item> itens = (ArrayList<Item>) q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return itens;
	}
	
	public ArrayList<Item> consultarPlano(int idplano) {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();
		Query q = sessao.createQuery("from modelo.Item where id_plano = " + idplano);
		ArrayList<Item> itens = (ArrayList<Item>) q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return itens;
	}
	

}
